package com.xunzhishimin.qa.web;

import com.xunzhishimin.qa.dao.AqroomDao;
import com.xunzhishimin.qa.entity.Aqroom;
import com.xunzhishimin.qa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Date;

@Controller
public class AQRoomController {
    @Autowired
    private AqroomDao aqRoomDao;

    @GetMapping({"/index", ""})
    public String index(Model model) {
        model.addAttribute("list", aqRoomDao.findAll());
        return "index";
    }

    @GetMapping("/aqroom/form")
    @PreAuthorize(value = "hasAnyAuthority('admin')")
    public String aqRoomForm(Aqroom aqroom, Model model) {
        if (aqroom != null && aqroom.getId() != null) {
            model.addAttribute("aqroom", aqRoomDao.findById(aqroom.getId()).get());
        }
        return "aqRoomForm";
    }

    @GetMapping("/aqroom/delete/{id}")
    @PreAuthorize(value = "hasAnyAuthority('admin')")
    @Transactional
    public String delete(@PathVariable("id") Long id, Model model) {
        aqRoomDao.delete(new Aqroom(id));
        return "redirect:/index";
    }

    @PostMapping("/aqroom/save")
    @PreAuthorize(value = "hasAnyAuthority('admin')")
    public String save(Aqroom aqRoom) {
        if (aqRoom.getId() == null) {
            User user = (User) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();
            aqRoom.setCreateBy(user);
            aqRoom.setCreateDate(new Date());
        } else {
            Aqroom aqroom1 = aqRoomDao.findById(aqRoom.getId()).get();
            aqRoom.setCreateDate(aqroom1.getCreateDate());
            aqRoom.setCreateBy(aqroom1.getCreateBy());
            /* aqRoom.setQuestions(aqRoom.getQuestions());*/
        }
        aqRoomDao.save(aqRoom);
        return "redirect:/index";
    }
}
